
package back;

import core.Login;
import core.TestData;
import core.User;
import dao.IUser;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

@ManagedBean(name="login")
@SessionScoped
public class LoginBean {
    
    @EJB
    IUser u;
    
    private User user = null;
    
    private String username;
    private String password;

    public LoginBean() {
    }

     public String getPassword() {
        return password;
    }

    public String getUsername() {
        return username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setUsername(String username) {
        this.username = username;
    }
    
    public String login() {
        User s = this.u.testLogin(new Login(getPassword(), getUsername()));
        if ( s != null) {
            TestData.loggedUser = s;
            TestData.actualTheme = s.getTheme();
            
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage("Vítejte zpět " + s.getName() + " " + s.getSurname() ));
            
            return "index";
        } else {
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage("Špatné uživatelské jméno nebo heslo"));

            return "login";
        }
    }

    public String logoutUser() {
        user = null;
        TestData.loggedUser = null;
        TestData.actualTheme = "sam";

        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage(null, new FacesMessage("Byl jste úspešně odhlášen"));

        return "login?faces-redirect=true";
    }
    
     public boolean isLoggedUser() {

        if (TestData.loggedUser != null) {
            return true;
        }
        return false;
    }

    public String getLoginName() {
        if (TestData.loggedUser != null) {
            return TestData.loggedUser.getName() +" " + TestData.loggedUser.getSurname();
        }
        return null;
    }
    
    public User getLoginUser(){
        return TestData.loggedUser;
    }


}
